package cn.zhaopin.starter.security.handler;

import com.alibaba.fastjson.JSON;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * Description: 自定义服务访问拒绝
 *
 * @author zuomin (myleszelic@outlook.com)
 * @date: 2021/09/28-16:08
 */
public class BasicServerAccessDeniedHandler implements ServerAccessDeniedHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException denied) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().set("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        Map<String, Object> result = new HashMap<>(4);
        result.put("code", "40003");
        result.put("httpCode", HttpStatus.FORBIDDEN);
        result.put("message", "访问拒绝");
        byte[] resultBytes = JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer dataBuffer = response.bufferFactory().wrap(resultBytes);
        return response.writeWith(Mono.just(dataBuffer));
    }
}
